package queues

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gproc"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gregex"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/consts"
	"hotgo/internal/controller/api/recorder"
	"hotgo/internal/dao"
	"hotgo/internal/library/queue"
	"hotgo/internal/model/entity"
)

func init() {
	queue.RegisterConsumer(RecorderOcr)
}

var RecorderOcr = &qRecorderOcr{}

type qRecorderOcr struct{}

// GetTopic 主题
func (q *qRecorderOcr) GetTopic() string {
	return consts.QueueRecorderOcrTopic
}

// Handle 处理消息
func (q *qRecorderOcr) Handle(ctx context.Context, mqMsg queue.MqMsg) (err error) {
	g.Log().Warning(ctx, "Ocr Handle", string(mqMsg.Body))
	var data recorder.QueueRecorder
	if err = json.Unmarshal(mqMsg.Body, &data); err != nil {
		return err
	}
	g.Dump(ctx, data)

	key := "ocrhandlenum"
	// --  @# TODO 进行OCR处理
	if !gfile.Exists(data.Path) {
		g.Redis().HIncrBy(ctx, key, gconv.String(data.ActivityId), 1)
		return gerror.NewCode(gcode.New(1, "", ""), "文件不存在")
	}
	PaddleEnv := "~/venvs/paddle_env/bin/paddleocr"
	command := fmt.Sprintf(
		"%s --image_dir '%s' --lang en --show_log false",
		PaddleEnv,
		data.Path,
	)

	//command := "source ~/venvs/paddle_env/bin/activate && paddleocr --image_dir " + data.Path + " --lang en --show_log false"
	result, err := gproc.ShellExec(ctx, command)
	if err != nil {
		g.Log().Error(ctx, err)
		g.Redis().HIncrBy(ctx, key, gconv.String(data.ActivityId), 1)
		return
	}
	g.Dump(111, result)
	match, _ := gregex.MatchAllString(data.Regexp, result)
	if len(match) == 0 {
		return
	}
	for _, v := range match {
		for _, vv := range v {
			var in entity.RecordOcr
			in.ActivityId = data.ActivityId
			in.CameraId = data.CameraId
			in.UserNo = vv
			in.Frame = data.Frame
			in.Time = gtime.Now()
			dao.RecordOcr.Ctx(ctx).Data(in).Insert()
		}

	}

	g.Redis().HIncrBy(ctx, key, gconv.String(data.ActivityId), 1)
	return nil
}
